package card

import (
	"core/command"
	"encoding/json"
	"fmt"
	"os"
	"runtime"
	"sync"
)

var (
	cardManger *CardsMgr
	once       sync.Once
)

type CardsMgr struct {
	pokerMap           map[string]*Combination
	typeToPokers       map[string][]*Combination
	cardTypeMap        map[string]command.CardType
	robotCardTypeArray []string
	cards              []string
}

type Combination struct {
	Type  string
	Score int
	Poker string
}

func CardsMgrGetMe() *CardsMgr {
	once.Do(func() {
		cardManger = &CardsMgr{
			pokerMap:           make(map[string]*Combination),
			typeToPokers:       make(map[string][]*Combination),
			cardTypeMap:        make(map[string]command.CardType),
			robotCardTypeArray: make([]string, 0),
			cards:              make([]string, 54),
		}
	})
	return cardManger
}

func (mgr *CardsMgr) Init(fileName string) {
	var path string
	if runtime.GOOS == "windows" {
		path = "./config/"
	} else {
		path = "../config/"
	}
	file, err := os.Open(path + fileName)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	var rule = make(map[string][]string)
	decoder := json.NewDecoder(file)
	err = decoder.Decode(&rule)
	if err != nil {
		fmt.Printf("json unmarsha1 err:%v \n", err)
		return
	}
	for pokerType, pokers := range rule {
		for score, poker := range pokers {
			cards := mgr.SortStr(poker)
			p := &Combination{
				Type:  pokerType,
				Score: score,
				Poker: cards,
			}
			mgr.pokerMap[cards] = p
			mgr.typeToPokers[pokerType] = append(mgr.typeToPokers[pokerType], p)
		}
	}
	mgr.initCardType()
	mgr.initCards()
}
